package face.pay.security.provider;

import face.pay.security.entity.SecurityUser;
import face.pay.security.service.ISecurityUserService;
import face.pay.security.token.UserNamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class UserNamePassWordProvider implements AuthenticationProvider {

    @Autowired
    private ISecurityUserService userService;

    private   PasswordEncoder passwordEncoder  = new BCryptPasswordEncoder();

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        UserNamePasswordToken ipUserToken = (UserNamePasswordToken)authentication;

        String domain = ipUserToken.getDomain();

        String userName  = ipUserToken.getPrincipal().toString();

        /**
         * 现根据 域名查出OEM 商户
         */
        SecurityUser userDetails = (SecurityUser) this.userService.loadUser(userName,domain);
        String pass_word_input  =  ipUserToken.getCredentials()!=null?ipUserToken.getCredentials().toString():"";
        String passWord =userDetails.getPassword();


        if(!this.passwordEncoder.matches(pass_word_input,passWord)){

           throw  new UsernameNotFoundException("用户名或密码错误");
        }

        UserNamePasswordToken authRequest = new UserNamePasswordToken(userDetails.getUsername(), userDetails.getPassword(),userDetails.getAuthorities());
        authRequest.setCurrentUser(userDetails.getCurrentUser());
        return authRequest;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UserNamePasswordToken.class.isAssignableFrom(authentication);
    }

    public PasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }

    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }


}
